#include "stock_data_loader.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <filesystem>
#include <algorithm>

// 静态变量
static std::map<std::string, std::vector<StockData>> g_stockDataMap;
static bool g_isInitialized = false;


int countCommas(const std::string& str) {
    int count = 0;
    for (char ch : str) {
        if (ch == ',') {
            ++count;
        }
    }
    return count;
}

// 从CSV文件加载数据
std::vector<StockData> loadFromCSV(const std::string& filepath) {
    std::vector<StockData> data;
    std::ifstream file(filepath);
    
    if (!file.is_open()) {
        std::cerr << "无法打开文件: " << filepath << std::endl;
        return data;
    }

    std::string line;
    // 跳过表头
    std::getline(file, line);

    // 读取数据行
    while (std::getline(file, line)) {
        std::stringstream ss(line);
        std::string field;
        StockData row;
        
        size_t number_of_commas = countCommas(line);
        if(7!=number_of_commas)
        {
            std::cerr << "文件格式错误: " << filepath  <<"\t几个逗号:"<<number_of_commas<< std::endl;
            abort();
        }

        // 解析每一列
        std::getline(ss, row.trade_date, ',');  // trade_date
        std::getline(ss, field, ',');           // trade_date (数字格式，跳过)
        std::getline(ss, row.ts_code, ',');     // ts_code
        
        std::getline(ss, field, ',');           // open
        row.open = std::stof(field);
        
        std::getline(ss, field, ',');           // high
        row.high = std::stof(field);
        
        std::getline(ss, field, ',');           // low
        row.low = std::stof(field);
        
        std::getline(ss, field, ',');           // close
        row.close = std::stof(field);
        
        std::getline(ss, field);           // vol
        row.vol = std::stof(field);
        
        // std::getline(ss, field, ',');           // EMA12
        // row.ema12 = std::stof(field);
        
        // std::getline(ss, field, ',');           // EMA26
        // row.ema26 = std::stof(field);
        
        // std::getline(ss, field, ',');           // MACD
        // row.macd = std::stof(field);
        
        // std::getline(ss, field, ',');           // MACD_Signal
        // row.macd_signal = std::stof(field);
        
        // std::getline(ss, field, ',');           // MACD_Histogram
        // row.macd_histogram = std::stof(field);

        data.push_back(row);
    }

    file.close();
    return data;
}

// 初始化股票数据加载器
STOCK_DATA_LOADER_API void initStockDataLoader() {
    if (!g_isInitialized) {
        g_stockDataMap.clear();
        g_isInitialized = true;
    }
}

// 加载指定目录下的所有CSV文件
STOCK_DATA_LOADER_API bool loadAllStockData(const char* directory) {
    if (!directory) {
        std::cerr << "目录路径为空" << std::endl;
        return false;
    }

    try {
        std::filesystem::path dir(directory);
        if (!std::filesystem::exists(dir) || !std::filesystem::is_directory(dir)) {
            std::cerr << "目录不存在或不是目录: " << directory << std::endl;
            return false;
        }

        // 遍历目录中的所有文件
        for (const auto& entry : std::filesystem::directory_iterator(dir)) {
            if (entry.path().extension() == ".csv") {
                std::string filename = entry.path().filename().string();
                std::string stockCode = filename.substr(0, filename.find_last_of('.'));// 这里的股票代码是包括.SZ后缀的
                
                // 加载CSV文件数据
                std::vector<StockData> data = loadFromCSV(entry.path().string());
                if (!data.empty()) {
                    g_stockDataMap[stockCode] = data;
                    //std::cout << "成功加载股票数据: " << stockCode << std::endl;
                }
            }
        }

        return true;
    } catch (const std::exception& e) {
        std::cerr << "加载股票数据时发生错误: " << e.what() << std::endl;
        return false;
    }
}

// 获取指定股票代码的数据
STOCK_DATA_LOADER_API const std::vector<StockData>* getStockData(const char* stockCode) {
    if (!stockCode) {
        return nullptr;
    }

    auto it = g_stockDataMap.find(stockCode);
    if (it != g_stockDataMap.end()) {
        return &(it->second);
    }
    return nullptr;
}

// 获取所有已加载的股票代码
STOCK_DATA_LOADER_API std::vector<std::string> getAllStockCodes() {
    std::vector<std::string> codes;
    for (const auto& pair : g_stockDataMap) {
        codes.push_back(pair.first);
    }
    return codes;
}

// 获取股票数据映射
STOCK_DATA_LOADER_API const std::map<std::string, std::vector<StockData>>& getStockDataMap() {
    return g_stockDataMap;
} 

